﻿using System;
using System.Net;
using System.Text;
using System.Threading;

namespace HttpServerDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Console.WriteLine("Hello World!");
            var httpListener = new HttpListener { AuthenticationSchemes = AuthenticationSchemes.Anonymous };
            httpListener.Prefixes.Add("http://+:8086/");
            httpListener.Start();

            new Thread(new ThreadStart(delegate
            {
                try
                {
                    Loop(httpListener);
                }
                catch (Exception)
                {
                    httpListener.Stop();
                }
            })).Start();

            Console.ReadKey();
        }

        private static void Loop(HttpListener httpListener)
        {
            HttpListenerContext context = httpListener.GetContext();
            HttpListenerRequest hRequest = context.Request;
            HttpListenerResponse hResponse = context.Response;
            while (true)
            {
                if (hRequest.HttpMethod == "POST")
                {
                    Console.WriteLine("POST:" + hRequest.Url);
                    foreach (var key in hRequest.Headers.AllKeys)
                        Console.WriteLine($"{key}:{hRequest.Headers[key]}");
                    byte[] res = Encoding.UTF8.GetBytes("OK");
                    hResponse.OutputStream.Write(res, 0, res.Length);
                }
                else if (hRequest.HttpMethod == "GET")
                {
                    Console.WriteLine("GET:" + hRequest.Url);     
                    foreach (var key in hRequest.Headers.AllKeys)
                        Console.WriteLine($"{key}:{hRequest.Headers[key]}");
                    byte[] res = Encoding.UTF8.GetBytes("OK");
                    hResponse.OutputStream.Write(res, 0, res.Length);
                }
            }
        }
    }
}